Shortest Word Distance III

Time: O(N); Space: O(1); medium

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

Note:

  • word1 and word2 may be the same and they represent two individual words in the list.

Example 1:

Input: words = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1=“makes”, word2=“coding”

Output: 1

Example 2:

Input: words = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1=“makes”, word2=“makes”

Output: 3

Note:

  • You may assume word1 and word2 are both in the list.

[1]:
class Solution1(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words List[string]
        :type word1 string
        :type word2 string
        :rtype: int
        """
        dist = float("inf")
        is_same = (word1 == word2)
        i, index1, index2 = 0, None, None

        while i < len(words):
            if words[i] == word1:
                if is_same and index1 is not None:
                    dist = min(dist, abs(index1 - i))
                index1 = i
            elif words[i] == word2:
                index2 = i

            if index1 is not None and index2 is not None:
                dist = min(dist, abs(index1 - index2))
            i += 1

        return dist
[2]:
s = Solution1()
words = ["practice", "makes", "perfect", "coding", "makes"]
word1="makes"
word2="coding"
assert s.shortestWordDistance(words, word1, word2) == 1
word1="makes"
word2="makes"
assert s.shortestWordDistance(words, word1, word2) == 3